const { Controller } = require("egg");

class ApifriendtaskController extends Controller {
  async saveFriendTask() {
    const { ctx } = this;
    const typename = ctx.request.body.typename;
    const ownerWxid = ctx.request.body.ownerWxid;
    const phones = ctx.request.body.phones;
    const content = ctx.request.body.content;

    try {
      const result = await ctx.service.phonedb.create(
        ownerWxid,
        typename,
        phones,
        content
      );
      //
      for (const item of result.records) {
        const resNew = await ctx.service.wxfriend.queryNewFriend(
          ownerWxid,
          item.phone
        );
        // console.log(resNew)
        await ctx.model.Phonedb.updateOne(
          { _id: item._id },
          {
            typename: resNew.typename,
            country: resNew.country,
            province: resNew.province,
            city: resNew.city,
            v3: resNew.v3,
            v4: resNew.v4,
            nick: resNew.nick,
            sex: resNew.sex,
            friendwxid: resNew.wxid,
            avatarMinUrl: resNew.avatarMinUrl,
            avatarMaxUrl: resNew.avatarMaxUrl,
          }
        );
      }
      ctx.body = {
        code: 20000,
        message: "手机号保存成功",
        data: result,
      };
    } catch (error) {
      console.error(error);
      ctx.body = {
        code: 50000,
        message: "保存失败",
        error: error.message,
      };
    }
  }

  async delFriendTask() {
    const { ctx, service } = this;
    const { ids } = ctx.request.body;
    const IdArray = Array.isArray(ids) ? ids : [ids];

    try {
      const results = await Promise.all(
        IdArray.map((Id) => service.phonedb.delPhone(Id))
      );

      ctx.body = {
        code: 20000,
        status: "ok",
        msg: "删除成功",
        data: {
          total: IdArray.length,
          success: results.filter((r) => r).length,
        },
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        status: "fail",
        msg: error.message,
      };
    }
  }

  async getFriendTask() {
    const { ctx } = this;
    const mywxid = ctx.request.body.ownerWxid;
    const field = ctx.request.body.field;
    const page = parseInt(ctx.request.body.page) || 1;
    const pageSize = parseInt(ctx.request.body.pageSize) || 20;

    const result = await ctx.service.phonedb.getPhone(
      mywxid,
      field,
      page,
      pageSize
    );
    ctx.body = result;
  }

  async editFriendTask() {
    const { ctx, service } = this;
    const { record } = ctx.request.body;
    try {
      const result = await service.phonedb.editPhone(record._id, record);
      ctx.body = {
        code: 20000,
        message: "修改成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        message: "修改失败",
        error: error.message,
      };
    }
  }

  async resetFriendTask() {
    const { ctx, service } = this;
    const { record } = ctx.request.body;
    try {
      const result = await service.phonedb.resetPhone(record._id);
      ctx.body = {
        code: 20000,
        message: "重置成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        message: "重置失败",
        error: error.message,
      };
    }
  }

  async saveGroupFriendTask() {
    const { ctx } = this;
    const ownerWxid = ctx.request.body.ownerWxid;
    const groupwxid = ctx.request.body.groupwxid;
    const friendlist = ctx.request.body.friendlist;
    const content = ctx.request.body.content;
    try {
      // Step 1: 提取所有要检查的 wxid，并先过滤掉和 ownerWxid 相同的
      const filteredBySelf = friendlist.filter((f) => f.wxid !== ownerWxid);
      const wxidsToCheck = filteredBySelf.map((f) => f.wxid);

      // Step 2: 批量查询 wxfriend 表中已存在的记录
      const existingFriends = await ctx.model.Wxfriend.find({
        ownerWxid,
        wxid: { $in: wxidsToCheck },
      }).select("wxid");

      const existingWxids = new Set(existingFriends.map((f) => f.wxid));

      // Step 3: 再次过滤掉已经存在的 wxid
      const filteredFriendlist = filteredBySelf.filter(
        (f) => !existingWxids.has(f.wxid)
      );
      const results = [];

      // Step 4: 只保存不存在的记录
      for (const friend of filteredFriendlist) {
        const existing = await ctx.model.Groupfriends.findOne({
          ownerWxid,
          friendwxid: friend.wxid,
        });

        if (!existing) {
          const result = await ctx.model.Groupfriends.create({
            ownerWxid,
            groupwxid,
            friendwxid: friend.wxid,
            content,
          });
          results.push(result);
        } else {
          console.warn(
            `Groupfriends 已存在记录：${ownerWxid} - ${friend.wxid}`
          );
        }
      }

      ctx.body = {
        code: 20000,
        message: "任务创建成功",
        data: results,
      };
    } catch (error) {
      console.error(error);
      ctx.body = {
        code: 50000,
        message: "创建失败",
        error: error.message,
      };
    }
  }
  async getGroupFriendTask() {
    const { ctx } = this;
    const mywxid = ctx.request.body.ownerWxid;
    const field = ctx.request.body.field;
    const page = parseInt(ctx.request.body.page) || 1;
    const pageSize = parseInt(ctx.request.body.pageSize) || 20;

    const result = await ctx.service.groupfriends.getGroupfriend(
      mywxid,
      field,
      page,
      pageSize
    );
    ctx.body = result;
  }

  async delGroupFriendTask() {
    const { ctx, service } = this;
    const { ids } = ctx.request.body;
    const IdArray = Array.isArray(ids) ? ids : [ids];

    try {
      const results = await Promise.all(
        IdArray.map((Id) => service.groupfriends.delGroupfriend(Id))
      );

      ctx.body = {
        code: 20000,
        status: "ok",
        msg: "删除成功",
        data: {
          total: IdArray.length,
          success: results.filter((r) => r).length,
        },
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        status: "fail",
        msg: error.message,
      };
    }
  }

  async editGroupFriendTask() {
    const { ctx, service } = this;
    const { record } = ctx.request.body;
    try {
      const result = await service.groupfriends.editGroupfriend(
        record._id,
        record
      );
      ctx.body = {
        code: 20000,
        message: "修改成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        message: "修改失败",
        error: error.message,
      };
    }
  }

  async resetGroupFriendTask() {
    const { ctx, service } = this;
    const { record } = ctx.request.body;
    try {
      const result = await service.groupfriends.resetGroupfriend(record._id);
      ctx.body = {
        code: 20000,
        message: "重置成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        message: "重置失败",
        error: error.message,
      };
    }
  }

  // 创建好友群发任务清单
  async createFriendSendTask() {
    const { ctx } = this;
    const { formData } = ctx.request.body;

    try {
      // 获取群发好友列表
      const friendList = await ctx.model.Wxfriend.find({
        ownerWxid: formData.ownerWxid,
        isreceive: true,
      });

      const createdTasks = [];

      for (const friend of friendList) {
        // 保存任务
        const task = await ctx.model.Sendallcontent.create({
          ownerWxid: formData.ownerWxid,
          wxid: friend.wxid,
          nick: friend.nick, // 添加昵称
          msgtype: formData.msgtype,
          content: formData.content,
          jumpUrl: formData.jumpUrl,
          jumpPath: formData.jumpPath,
          gh: formData.gh,
          appid: formData.appid,
          path: formData.path,
        });

        createdTasks.push(task);
      }

      ctx.body = {
        code: 20000,
        message: "创建任务成功",
        data: createdTasks,
      };
    } catch (error) {
      console.error("创建任务失败:", error);
      ctx.body = {
        code: 50000,
        message: "创建任务失败",
        error: error.message,
      };
    }
  }
  // 创建群群发任务清单
  async createGroupSendTask() {
    const { ctx } = this;
    const { formData } = ctx.request.body;

    try {
      // 获取群发好友列表
      const groupList = await ctx.model.Wxgroup.find({
        ownerWxid: formData.ownerWxid,
        isreceive: true,
      });

      const createdTasks = [];

      for (const friend of groupList) {
        // 保存任务
        const task = await ctx.model.Sendallcontent.create({
          ownerWxid: formData.ownerWxid,
          wxid: friend.wxid,
          nick: friend.nick,
          msgtype: formData.msgtype,
          content: formData.content,
          jumpUrl: formData.jumpUrl,
          jumpPath: formData.jumpPath,
          gh: formData.gh,
          appid: formData.appid,
          path: formData.path,
        });

        createdTasks.push(task);
      }

      ctx.body = {
        code: 20000,
        message: "创建任务成功",
        data: createdTasks,
      };
    } catch (error) {
      console.error("创建任务失败:", error);
      ctx.body = {
        code: 50000,
        message: "创建任务失败",
        error: error.message,
      };
    }
  }

  async getSendTask() {
    const { ctx } = this;
    const mywxid = ctx.request.body.ownerWxid;
    const field = ctx.request.body.field;
    const page = parseInt(ctx.request.body.page) || 1;
    const pageSize = parseInt(ctx.request.body.pageSize) || 20;
    // console.log("获取群发任务", mywxid, field, page, pageSize);
    try {
      // 构建查询条件
      let query = { ownerWxid: mywxid };

      // 处理查询参数
      if (field.nick) {
        query.nick = new RegExp(field.nick, "i"); // i表示不区分大小写
      }
      if (field.tags && field.tags.length > 0) {
        query.tags = { $in: [field.tags] }; // 查找tags数组中包含指定tag的文档
      }
      if (field.isreceive !== undefined) {
        query.isreceive = field.isreceive;
      }
      if (field.status !== undefined) {
        query.status = field.status;
      }
      // 计算跳过的文档数量
      const skip = (page - 1) * pageSize;

      // 获取总数
      const total = await ctx.model.Sendallcontent.countDocuments(query);

      // 使用 skip 和 limit 实现分页查询
      const data = await ctx.model.Sendallcontent.find(query)
        .skip(skip)
        .limit(pageSize)
        .sort({
          createTime: -1, // 其次按创建时间降序
        })
        .exec();
      ctx.body = {
        code: 20000,
        msg: "获取成功",
        data: {
          count: total,
          list: data,
        },
      };
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("获取失败:", error.message);
      ctx.body = {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
        data: {
          count: 0,
          list: [],
        },
      };
    }
  }

  async resetSendask() {
    const { ctx, service } = this;
    const { record } = ctx.request.body;
    try {
      const result = await service.sendmsgtask.resetSendmsgtask(record._id);
      ctx.body = {
        code: 20000,
        message: "重置成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        message: "重置失败",
        error: error.message,
      };
    }
  }

  async deleteSentTasks() {
    const { ctx } = this;
    const { ownerWxid } = ctx.request.body;
    try {
      const result = await ctx.model.Sendallcontent.deleteMany({ownerWxid, status: 1});
      ctx.body = {
        code: 20000,
        message: "删除成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        message: "删除失败",
        error: error.message,
      };
    }
  }

  async resetFailedTasks() {
    const { ctx } = this;
    const { ownerWxid } = ctx.request.body;
    try {
      const result = await ctx.model.Sendallcontent.updateMany(
        { ownerWxid, status: 2 },
        { $set: { status: 0 } }
      );
      ctx.body = {
        code: 20000,
        message: "重置成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        message: "重置失败",
        error: error.message,
      };
    }
  }

  async clearAllTask() {
    const { ctx } = this;
    const { ownerWxid } = ctx.request.body;
    try {
      const result = await ctx.model.Sendallcontent.deleteMany({ ownerWxid });
      ctx.body = {
        code: 20000,
        message: "清理成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 50000,
        message: "清理失败",
        error: error.message,
      };
    }
  }
  async test() {
    const { ctx, service } = this;
    const now = new Date();
    const startTime = new Date(now.getTime() - 30000 + 8 * 60 * 60 * 1000); // 提前30秒开始扫描
    const endTime = new Date(now.getTime() + 30000 + 8 * 60 * 60 * 1000); // 包含未来30秒的任务

    const tasks = await ctx.model.Sendallcontent.find({
      triggerTime: { $gte: startTime, $lte: endTime },
      istask: true,
      status: 0, // 只处理未发送的任务
    }).limit(100);

    if (tasks.length === 0) {
      ctx.logger.info("send:该时间段没有群发任务");
      return;
    }

    for (const task of tasks) {
      try {
        // 根据 msgtype 调用不同的发送方法
        let result = {};
        switch (task.msgtype) {
          case "text":
            result = await service.sendmsg.sendText2(
              task.wxid,
              task.content,
              task.ownerWxid
            );
            break;
          case "image":
            result = await service.sendmsg.sendImage(
              task.wxid,
              task.path,
              task.ownerWxid
            );
            break;
          case "file":
            result = await service.sendmsg.sendFile(
              task.wxid,
              task.path,
              task.mywxid
            );
            break;
          case "gh":
            result = await service.sendmsg.sendApplet(
              task.wxid,
              task.gh,
              task.ownerWxid
            );
            break;
          case "share":
            result = await service.sendmsg.sendShareUrl(
              task.wxid,
              task.jumpUrl,
              task.ownerWxid
            );
            break;
          default:
            ctx.logger.warn(`未知的消息类型: ${task.msgtype}`);
            continue;
        }

        if (result.code === 200) {
          await ctx.model.Sendallcontent.updateOne(
            { _id: task._id },
            { $set: { status: 1 } }
          );
          ctx.logger.info(`✅ 发送成功: ${task.msgtype}`);
        } else {
          await ctx.model.Sendallcontent.updateOne(
            { _id: task._id },
            {
              $inc: { failCount: 1 },
              $set: { lastErrorMsg: result.msg },
            }
          );
          ctx.logger.error(`❌ 发送失败: ${result.msg}`);
        }
      } catch (error) {
        ctx.logger.error(`❌ 处理任务 ${task._id} 出现异常:`, error);
      }
    }
  }
}

module.exports = ApifriendtaskController;
